/*
 * @Author: wangdazhuang
 * @Date: 2024-08-23 10:41:49
 * @LastEditTime: 2025-01-27 10:00:29
 * @LastEditors: wangdazhuang
 * @Description: 
 * @FilePath: /pornhub_app/lib/utils/ad_jump.dart
 */
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' as ddd;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/advertisements/ad_resp_model.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/services/storage_service.dart';
import 'package:pornhub_app/services/user_service.dart';
import 'package:pornhub_app/utils/logger.dart';
import 'package:pornhub_app/views/webview/webview_page.dart';
import 'package:universal_html/html.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../env/environment_service.dart';

const urlPrefix = 'pdd://pdd/';

abstract class JumpProtocolEnum {
  //长视频 "pdd://pdd/video?videoId=123"
  static const video = 'video';

  //活动 "pdd://pdd/activity?url=https://www.baidu.com";
  static const activity = "activity";

  //会员  "pdd://pdd/rech";
  static const rech = 'rech';

  //钱包  "pdd://pdd/wall";
  static const wall = 'wall';

  //分享  "pdd://pdd/share";
  static const share = 'share';

  //加群  "pdd://pdd/group";
  static const group = 'group';

  //博主主页  "pdd://pdd/blogger?bloggerId=123";
  static const blogger = 'blogger';

  //游戏"pdd://pdd/game?gameId=123";
  static const game = 'game';

  //AI"pdd://pdd/ai";
  static const ai = 'ai';
}

//点击上报
void clickAdReport(params) async {
  await httpInstance.post(url: 'sys/click/upload', body: params);
}

// 跳转外部链接
void jumpExternalAddress(String url, params) async {
  if (params != null) {
    clickAdReport(params);
  }
  Uri? path = Uri.tryParse(url);
  if (path == null) {
    logger.d('jumpExternalAddress bad url');
    return;
  }

  // logger.d('jumpExternalAddress url:$url');
  // logger.d('jumpExternalAddress path:$kIsWeb');

  if (kIsWeb) {
    window.open(url, '_blank');
    // window.location.href = url;
    // ddd.Navigator.push(
    //   Get.context!,
    //   MaterialPageRoute(builder: (BuildContext context) {
    //     return AppWebViewPage(
    //       url: url,
    //     );
    //   }),
    // );
    // launchUrlString(
    //   url,
    //   ///mode externalApplication 在打开的时候不会被底下的home顶上去
    //   mode: LaunchMode.externalApplication,
    //   webViewConfiguration: const WebViewConfiguration(),
    //   browserConfiguration: const BrowserConfiguration(showTitle: true),
    // );
    return;
  }
  try {
    if (!await canLaunchUrl(path)) {
      logger.d('jumpExternalAddress can not launch url:$url');
      return;
    }

    if (!await launchUrl(path)) {
      logger.d('jumpExternalAddress launch fail url:$url');
    }
  } catch (e) {
    logger.d('jumpExternalAddress launch fail url:$url e:$e');
  }
}

//跳转内部
void jumpInternalAddress(String url) {
  final adJumpAddress = url.substring(urlPrefix.length);
  if (adJumpAddress.startsWith(JumpProtocolEnum.video)) {
    final videoId = url.split('=')[1];
    //跳视频播放
    Get.toPlayVideo(videoId: int.parse(videoId));
  }

  if (adJumpAddress.startsWith(JumpProtocolEnum.blogger)) {
    final id = url.split('=')[1];
    //跳博主详情
    // Get.toBloggerDetail(userId: int.parse(id));
    return;
  }

  // if (adJumpAddress.startsWith(JumpProtocolEnum.game)) {
  //   final id = url.split('=')[1];
  //   //游戏详情
  //   ddd.Navigator.push(
  //     Get.context!,
  //     MaterialPageRoute(
  //       builder: (context) => GameDetailViewPage(
  //         id: int.parse(id),
  //       ),
  //     ),
  //   );
  //   return;
  // }

  if (adJumpAddress.startsWith(JumpProtocolEnum.activity)) {
    //跳活动
    final storageService = Get.find<StorageService>();
    final token = storageService.token;
    final jumpurl = '${url.split('=')[1]}?token=$token';
    ddd.Navigator.push(
      Get.context!,
      MaterialPageRoute(builder: (BuildContext context) {
        return AppWebViewPage(
          url: jumpurl,
        );
      }),
    );
    return;
  }
  if (adJumpAddress.startsWith(JumpProtocolEnum.rech)) {
    //跳会员
    Get.toVip(tabInitIndex: 0);

    return;
  }

  if (adJumpAddress.startsWith(JumpProtocolEnum.wall)) {
    //跳钱包
    Get.toVip(tabInitIndex: 1);
    return;
  }
  if (adJumpAddress.startsWith(JumpProtocolEnum.share)) {
    //跳分享
    Get.toShare();
    return;
  }
  if (adJumpAddress.startsWith(JumpProtocolEnum.group)) {
    //跳加群
    // Get.toNamed(Routes.share);
    Get.toNamed(Routes.mine_fans_followers, parameters: {'title': "加群聊骚"});
    return;
  }
  if (adJumpAddress.startsWith(JumpProtocolEnum.ai)) {
    //跳AI
    Get.toNamed(Routes.aiHome);
    return;
  }
}

///在线客服
void kOnLineService({String onLineServiceUrl = ""}) {
  String url = onLineServiceUrl;
  if (url == "" || url.trim().isEmpty) {
    final us = Get.find<UserService>();
    if (us.url.isEmpty) {
      return;
    }
    url = (Environment.kbaseAPI + us.url).replaceFirst("api//", "");
  }
  launchUrlString(
    url,
    mode: LaunchMode.externalApplication,
    webViewConfiguration: const WebViewConfiguration(),
    browserConfiguration: const BrowserConfiguration(showTitle: true),
  );
}

void kAdjump(dynamic ad, adId, [type = 1]) {
  final params = {'adId': adId, 'type': type};
  if (ad == null) return;
  if (ad is String) {
    if (ad.startsWith(urlPrefix)) {
      //跳内部
      jumpInternalAddress(ad);
    } else {
      jumpExternalAddress(ad, params);
    }
  }
  if (ad is AdvertisementInfos && ad.adJump != null) {
    if (ad.adJump!.startsWith(urlPrefix)) {
      //跳内部
      jumpInternalAddress(ad.adJump!);
    } else {
      jumpExternalAddress(ad.adJump!, params);
    }
  }
}

void kAdInfoJump(AdvertisementInfos ad, [int type = 1]) =>
    kAdjump(ad, ad.adId, type);
